package com.colis.quartz.provider.sms.service.impl;

import com.colis.quartz.annotation.TranService;
import com.colis.quartz.common.enumerate.QuartzStatusEnum;
import com.colis.quartz.common.extension.BaseJpaService;
import com.colis.quartz.module.sms.QuartzTask;
import com.colis.quartz.provider.sms.mapper.QuartzTaskMapper;
import com.colis.quartz.utils.SchedulerJobUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

/**
 * <p> 描述：定时任务 服务实现类 </p>
 *
 * @author wlp
 * @version 1.0.0
 * @date 2022/1/13 9:34
 */
@Slf4j
@TranService
public class QuartzTaskServiceImpl extends BaseJpaService<QuartzTaskMapper, QuartzTask> {

    @Resource
    private Scheduler scheduler;

    @Resource
    private QuartzTaskMapper quartzTaskMapper;

    @PostConstruct
    private void start() {
        List<QuartzTask> quartzTaskList = quartzTaskMapper.findAll();
        for (QuartzTask quartzTask : quartzTaskList) {
            if (quartzTask.getQuartzStatus() == QuartzStatusEnum.NORMAL) {
                try {
                    SchedulerJobUtil.addJob(scheduler, quartzTask);
                } catch (SchedulerException e) {
                    log.error(e.getMessage());
                }
            }
        }
    }

    @SneakyThrows
    public void saveJob(QuartzTask quartzTask) {
        quartzTaskMapper.saveAndFlush(quartzTask);
        SchedulerJobUtil.addJob(scheduler, quartzTask);
    }
}